package main

import (
	"fmt"
	"net"
	"strings"
)

type User struct {
	UserName      string
	OtherUserName string
	Msg           string
	ServerMsg     string
}

var (
	userMap = make(map[string]net.Conn)
	user    = new(User)
)

func main() {
	// 创建地址  版本可以运行
	addr, _ := net.ResolveTCPAddr("tcp4", "localhost:8899")
	// 创建监听器
	tcp, _ := net.ListenTCP("tcp4", addr)
	for {
		// 通过监听器创建连接对象
		conn, _ := tcp.Accept()
		go func() {
			for {
				// 读取数据
				b := make([]byte, 1024)
				// 获取连接
				n, _ := conn.Read(b)
				array := strings.Split(string(b[:n]), "-")
				user.UserName = array[0]
				user.OtherUserName = array[1]
				user.Msg = array[2]
				user.ServerMsg = array[3]
				userMap[user.UserName] = conn
				if v, ok := userMap[user.OtherUserName]; ok && v != nil {

					n, err := v.Write([]byte(fmt.Sprintf("%s-%s-%s-%s", user.UserName, user.OtherUserName, user.Msg, user.ServerMsg)))
					if n <= 0 || err != nil {
						delete(userMap, user.OtherUserName)
						// 关闭连接
						conn.Close()
						v.Close()
						fmt.Println("if....")
						break
					}
					fmt.Println("发送消息成功")
					fmt.Println(user.UserName)
					fmt.Println(user.OtherUserName)
					fmt.Println(user.Msg)
				} else {
					user.ServerMsg = "对方不在线"
					conn.Write([]byte(fmt.Sprintf("%s-%s-%s-%s", user.UserName, user.OtherUserName, user.Msg, user.ServerMsg)))
				}
			}

		}()

	}

}
